﻿using UnityEngine;
using UnityEngine;
using System;
using System.Collections;

public class BloodEffect : MonoBehaviour {
	
	public GameObject bloodEffect;
	public Camera bloodCamera;
	public GameObject[] screenBloodEffects;

	private bool isScreenEffectPlaying = false;

	public bool enableScreenEffect;

	public void Play(Vector3 position, Quaternion quaternion) {
		GameObject.Instantiate(bloodEffect, position, quaternion);
		if (enableScreenEffect) {
			//Not play every time
			if (!isScreenEffectPlaying) {
				isScreenEffectPlaying = true;
				PlayScreenBlood();
			}
		}
	}

	public void PlayScreenBlood() {
		System.Random random = new System.Random();
		int ind = random.Next(0, (screenBloodEffects.Length - 1));
		GameObject obj = Instantiate(screenBloodEffects[ind]) as GameObject;
		obj.transform.parent = bloodCamera.transform;

		obj.transform.localPosition = new Vector3(0.0f, 0.0f ,3.0f);
		obj.transform.localRotation = Quaternion.Euler(0.0f, -90.0f, 90.0f);
		obj.transform.localScale = new Vector3(0.3f, 0.3f, 0.3f);
		StartCoroutine(FadeScreenBlood(obj));
	}

	IEnumerator FadeScreenBlood(GameObject effectObj) {
		Color color = effectObj.renderer.material.GetColor("_Color");
		float durationTime = 2.0f;
		float changeInterval = 0.1f;

		float changeTime = durationTime / changeInterval;

		float change = color.a / changeTime;
		//Debug.LogError(string.Format("{0}", change));
		for(int i = 0; i < changeTime; ++i) {
			color.a -= change;
			if (color.a < 0)
				color.a = 0;
			effectObj.renderer.material.SetColor("_Color", color);
			yield return new WaitForSeconds(changeInterval);
		}

		Destroy(effectObj);
		isScreenEffectPlaying = false;
	}

}
